Number of enclaves

Time: O(MxN); Space: O(MxN); medium

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: A =

[
    [0,0,0,0],
    [1,0,1,0],
    [0,1,1,0],
    [0,0,0,0]
]

Output: 3

Explanation:

  • There are three 1s that are enclosed by 0s, and one 1 that isn’t enclosed because its on the boundary.

Example 2:

Input: A =

[
    [0,1,1,0],
    [0,0,1,0],
    [0,0,1,0],
    [0,0,0,0]
]

Output: 0

Explanation:

  • All 1s are either on the boundary or can reach the boundary.

Constraints:

  • 1 <= len(A) <= 500

  • 1 <= len(A[i]) <= 500

  • 0 <= A[i][j] <= 1

  • All rows have the same size.

Hints:

  1. Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map.

  2. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.

[3]:
class Solution1(object):
    """
    Time: O(M*N)
    Space: O(M*N)
    """
    def numEnclaves(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        directions = [(0, -1),
                      (0,  1),
                      (-1, 0),
                      (1,  0)
                     ]

        def dfs(A, i, j):
            if not (0 <= i < len(A) and 0 <= j < len(A[0]) and A[i][j]):
                return

            A[i][j] = 0
            for d in directions:
                dfs(A, i + d[0], j + d[1])

        for i in range(len(A)):
            dfs(A, i, 0)
            dfs(A, i, len(A[0])-1)

        for j in range(1, len(A[0])-1):
            dfs(A, 0, j)
            dfs(A, len(A)-1, j)

        return sum(sum(row) for row in A)
[4]:
s = Solution1()

A = [
  [0,0,0,0],
  [1,0,1,0],
  [0,1,1,0],
  [0,0,0,0]
]
assert s.numEnclaves(A) == 3

A = [
  [0,1,1,0],
  [0,0,1,0],
  [0,0,1,0],
  [0,0,0,0]
]
assert s.numEnclaves(A) == 0